<?php
// +-------------------------------------------------------------------
// | 
// +-------------------------------------------------------------------
// | Copyright (c) 2009-2016 All rights reserved.
// +-------------------------------------------------------------------
namespace Kcdns\Service\Site;

/**
 * 用于模板快速获取数据
 *
 * @package Service\Util
 *
 * @author Sadaharu#1 <hechengyuan@ucfgroup.com>
 */
use Kcdns\Common\Api\CategoryApi;

class Article
{
    public static function listsAll($cate_name, $page, $page_size)
    {
        $where = [
            'a.status' => 1,
            'b.name' => $cate_name
        ];

        $list = M('')
            ->field('a.*,c.*,b.name as cate_name,b.title as cate_title')
            ->table('__DOCUMENT__ a')
            ->join('__CATEGORY__ b on b.id=a.category_id')
            ->join('__DOCUMENT_ARTICLE__ c on c.id=a.id')
            ->where($where)
            ->order('a.id desc')
            ->page($page, $page_size)
//            ->fetchSql(true)
            ->select();

        $count = M()
            ->table('__DOCUMENT__ a')
            ->join('__CATEGORY__ b on b.id=a.id')
            ->where($where)
            ->count();

        $cate_title = M('category')->where([
            'name' => $cate_name
        ])->getField('title');

        return [
            $list,
            $count,
            $cate_title
        ];
    }

    public static function detailSingle($cate_name)
    {
        $result = M()
            ->field('a.*,b.*,c.name as cate_name,c.title as cate_title')
            ->table('__DOCUMENT__ a')
            ->join('__DOCUMENT_SINGLE__ b on b.id=a.id')
            ->join('__CATEGORY__ c on c.id=a.category_id')
            ->where([
                'c.name' => $cate_name,
                'a.status' => 1,
            ])
            ->find();

        return $result;
    }

    public static function detail($id, $field = 'id')
    {
        $result = M()
            ->field('a.*,b.*,c.name as cate_name,c.title as cate_title')
            ->table('__DOCUMENT__ a')
            ->join('__DOCUMENT_ARTICLE__ b on b.id=a.id')
            ->join('__CATEGORY__ c on c.id=a.category_id')
            ->where([
                "a.$field" => $id,
                'a.status' => 1,
            ])
            ->find();

        if (!$result) {
            throw new \Exception("无效的文章id");
        }

        if ($result) {
            $result['cover_path'] = get_cover($result['cover_id'], 'path');
        }

        return $result;
    }

    public static function lists($cate_name, $page = 1, $page_size = 5)
    {
        $where = [
            'a.status' => 1,
            'b.name' => $cate_name
        ];

        $list = M('')
            ->field('a.*,b.name as cate_name,b.title as cate_title')
            ->table('__DOCUMENT__ a')
            ->join('__CATEGORY__ b on b.id=a.category_id')
            ->where($where)
            ->order('a.id desc')
            ->page($page, $page_size)
            ->select();

        foreach ($list as &$row) {
            $row['cover_path'] = get_cover($row['cover_id'], 'path');
        }

        $count = M()
            ->table('__DOCUMENT__ a')
            ->join('__CATEGORY__ b on b.id=a.category_id')
            ->where($where)
            ->count();

        $cate_title = M('category')->where([
            'name' => $cate_name
        ])->getField('title');

        return [
            (array)$list,
            $count,
            $page_total = ceil($count / $page_size),
            $cate_title
        ];
    }

    public static function pageList($page = 0, $cateid = 0, $where = array(), $showcate = false, $showuser = false)
    {
        $timestamp = I('get.timestamp');
        $condition = array(
            'addfield' => 'uuid,level',
            'model' => 'article',
            'extend' => 'sign,goodsurl',
            'limit' => '10',
            'order' => ' level desc, create_time desc, id DESC'
        );

        //uuid + timestamp 翻页验证
        $condition['where'] = array();
        if ($page) {
            if (md5($page + 'kcdns') !== $timestamp) {
                throw new \Exception('签名失败');
            }
            $row = D('Document')->field('id,level,create_time')->where(array('uuid' => $page))->find();
            $row && $condition['where'] = array(
                '_complex' => array(
                    'level' => array('lt', $row['level']),
                    '_complex' => array(
                        'level' => $row['level'],
                        '_complex' => array(
                            'create_time' => array('lt', $row['create_time']),
                            '_complex' => array(
                                'create_time' => $row['create_time'],
                                'id' => array('lt', $row['id']),
                            ),
                            '_logic' => 'or'
                        ),
                        '_logic' => 'and'
                    ),
                    '_logic' => 'or'
                )
            );
        }
        $where && $condition['where'] = array_merge($condition['where'], $where);
        $cateid && $condition['cateid'] = $cateid;

        $list = self::getList($condition);

        $Api = new CategoryApi();

        $uids = array_column($list, 'uid');

        $writers = D('Member')->where(
            array('uid' => array('in', implode(',', $uids)))
        )->field('uid,uuid,cover_id,nickname,sex')->select();
        $writerList = array_combine(array_column($writers, 'uid'), $writers);

        //将扩展字段加入到文章列表中
        foreach ($list as &$v) {
            $v['sign'] = split(',', $v['sign']);
            $v['timestamp'] = md5($v['uuid'] + 'kcdns');

            $cate = $Api->get_category($v['category_id']);
            $v['cate'] = array(
                'name' => $cate['name'],
                'title' => $cate['title']
            );

            if (array_key_exists($v['uid'], $writerList)) {
                $v['writer'] = $writerList[$v['uid']];
            }

        }
        //if ($showuser) self::parseCate($list);
        //if ($showuser) self::parseUser($list);

        return $list;
    }

    /**
     * $tag = array(
     * 'cateid' => 51,
     * 'row'=>10.
     * 'field'=>'*',
     * 'addfield'=>0,
     * 'pos'=>0,
     * 'where'=>0,
     * 'limit'=>0,
     * 'order'=>0
     * );
     */
    public static function getList($tag)
    {
        $row = empty($tag['row']) ? 10 : $tag['row'];
        $field = empty($tag['field']) ? 'id,uid,title,category_id,description,cover_id,seo_title,seo_keyword,seo_description,create_time,update_time,comment,view' : $tag['field'];
        $field .= empty($tag['addfield']) ? '' : ',' . $tag['addfield'];
        $category = (int)$tag['cateid'];
        $pos = $tag['pos'];
        $where = $tag['where'];
        $display = $tag['display'] ? $tag['display'] : 1;
        $limit = $tag['limit'] ? $tag['limit'] : '10';
        $withModel = $tag['model'] ? $tag['model'] : 'article';
        $withExtend = $tag['extend'];
        $order = $tag['order'] ? $tag['order'] : 'create_time desc, id DESC';

        $page = !empty($_GET["p"]) ? $_GET["p"] : 1;

        $map = array(
            'display' => $display,
            'create_time' => array(
                'lt',
                NOW_TIME
            ),
            '_string' => ' (status=1) AND (deadline = 0 OR deadline > ' . NOW_TIME . ')'
        );

        $category && $map['category_id'] = $category;

        $where && $map = array_merge($map, $where);

        /* 设置推荐位 */
        is_numeric($pos) and $pos and $map[] = "position & {$pos} = {$pos}";
        $RS = M('Document')->field($field)->where($map)->order($order)->limit($limit)->select();

        //取副表
        if ($extendRS = self::getExtend($RS, $withModel, $withExtend)) {
            foreach ($RS as &$v) {
                $v = array_merge($v, $extendRS[$v['id']]);
            }
        }
        return $RS;
    }

    /**
     * Short description.
     * @param   type $varname description
     * @return  type    description
     * @access  private
     * @static  makes the class property accessible without needing an instantiation of the class
     * @author hayden <hayden@yeah.net>
     */
    private static function getExtend($RS, $withModel, $withExtend)
    {
        if (!$withModel || !$withExtend || !$RS) {
            return false;
        }
        $allIds = array_column($RS, 'id');
        $map = array(
            'id' => array(
                'in', implode(',', $allIds)
            )
        );
        $extendRS = M('Document_' . $withModel)->where($map)->field('id,' . $withExtend)->select();
        if ($extendRS) {
            //提取ID序列
            $extendID = array_column($extendRS, 'id');
            //数据集下标转文章ID
            $extendRS = array_combine($extendID, $extendRS);
        }
        return $extendRS;

    } // end func

    // 
    public static function myGetList($category_id, $page = 1, $size = 20)
    {
        filter($category_id, 'required;int;');

        $where = [
            'status' => 1,
            'category_id' => $category_id
        ];

        $join = '__DOCUMENT INNER JOIN __DOCUMENT_ARTICLE__ ON __DOCUMENT.id = __DOCUMENT_ARTICLE__.id';

        $count = M('document')->where($where)->join($join)->count();
        $list = M('document')->where($where)->join($join)->page($page . ',' . $size)->order('level desc,create_time desc')->select();

        return compact('count', 'list');
    }

    public static function myGetDetail($id)
    {
        filter($id, 'required;int');

        $where = 'status=1 AND __DOCUMENT.id=' . $id;

        $join = '__DOCUMENT INNER JOIN __DOCUMENT_ARTICLE__ ON __DOCUMENT.id = __DOCUMENT_ARTICLE__.id';

        return M('document')->where($where)->join($join)->find();
    }
}
